/************************************************************************
/*<input type="number" [dataType="int"] [field="@field"] digits=[{number}|
                        APP_ForgCurrAmtDec|
                         APP_BaseAmtDec]   
/>
************************************************************************/
/**
 * Created by long on 27/07/2014.
 */
HRP.directive('lang',
    [
      '$application',
    function (
        $app
        ) {
        return {
            restrict: "A",
            template: "<div  ng-transclude ></div>",
            replace: true,
            transclude: true,
            scope: false,
            compile: function (e, a) {
                return function (s, e, a) {
                    var scope =$app.$instance().$loader.getScope(s, a);
                    var config = $app.$instance().$loader.$generateConfig(scope, e, a);
                    
                    config.listeners.afterRender=function (sender) {
                        var txt = $app.$instance().$lang.getCaption(e.text(), s.$$$module,
                                                             $app.$instance().$lang.getLanguageCode());
                                sender.setText(txt);
                                if (a.required == "true") {
                                    sender.addClass("x-required");
                                }
                                e.remove();
                            };
                    if (a.id) {
                        config.id = a.id + "_" + scope.$id;
                    }
                    var parent = $(e[0]).parent("*[toolbar]");
                    if (parent.length > 0) {
                        config.xtype = "label";
                        $app.$linkToParent(e[0], "items", config);
                        e.remove();
                        return;
                    }
                    config.renderTo = e.parent()[0];
                    var lbl = new Ext.form.Label(config);
                }
            }
        }
    }
    ]);

HRP.directive('sencha',
    [
        '$uiElements',
        '$application',
        function (
                  $uiElements,
                  $app
                  ) {
            return {
                restrict: "A",
                template: "<div  ng-transclude></div>",
                replace: true,
                transclude: true,
                scope: false,
                compile: function (e, a) {
                    return function (s, e, a) {
                        var scope = $app.$instance().$loader.getScope(s, a);
                        var config = $app.$instance().$loader.$generateConfig(scope, e, a);
                        config.renderTo = e[0];
                        if (a.width) {
                            config.width = a.width * 1;
                        }
                        if (a.sencha == "number") {
                                var cmp = $uiElements.createNumericInput(scope, e, a, config);
                            }
                    }
                }
            }
        }]);
HRP.directive('type',
    [
        '$uiElements',
        '$application',
        function (
                  $uiElements,
                  $app
                  ) {
            return {
                restrict: "A",
                template: "<div  ng-transclude></div>",
                replace: true,
                transclude: true,
                scope: false,
                compile: function (e, a) {
                    return function (s, e, a) {
                        var scope = $app.$instance().$loader.getScope(s, a);
                        var config = $app.$instance().$loader.$generateConfig(scope, e, a);
                     
                        if (a.width) {
                            config.width = a.width * 1;
                        }
                        if (a.type == 'text') {
                            if (a.xTypeX == "number") {
                                var cmp = $uiElements.createNumericInput(scope, e, a, config);
                            }
                            else {
                                var cmp = $uiElements.createTextField(scope, e, a, config);
                            }
                        }
                        if(a.type=='button'){
                            var cmp = $uiElements.createButton(scope,e,a,config);
                        }
                        if(a.type=="date"){
                            var cmp = $uiElements.createDatePicker(scope, e, a, config);
                        }
                        if (a.type == "number") {
                            p = $uiElements.createNumericInput(scope, e, a, config);
                        }
                        if (a.type == "radio") {
                            p = $uiElements.createRadioButton(scope, e, a, config);
                        }
                        if (a.type == "checkbox") {
                            p = $uiElements.createCheckBox(scope, e, a, config);
                        }
                        if (a.type == "combobox") {
                         
                            p = $uiElements.createCombobox(scope, e, a, config);
                        }
                        if (a.type == "password") {
                            p = $uiElements.createPassword(scope, e, a, config);
                        }
                    }
                }
            }
        }]);
HRP.service("$uiElements",
    [
        "$application",
        "$combobox",
        function ($app,
                  $cbo) {
            return{
                createTextField:function(s,e,a,config){
                    config.listeners.render=function(sender){
                        if(a.field){
                            sender.setValue(s.$eval(a.field));
                            s.$watch(a.field, function (n, o) {
                                if (n != o) {
                                    sender.$prevent = true;
                                    sender.setValue(n);
                                    sender.$prevent = false;
                                }
                            });
                        }


                    };
                    config.listeners.change = function (sender, value) {
                        if (sender.$prevent) return;
                        if(a.field){
                            $app.$instance().$parse(a.field).assign(s,value);
                            s.$digest();

                        }
                    };
                    var parent = $(e[0]).parent("*[toolbar]");
                    if (parent.length > 0) {
                        config.xtype = "textfield";
                        $app.$linkToParent(e[0], "items", config);
                        e.remove();
                        return;
                    }
                    config.renderTo = e[0];
                    var cmp = new Ext.form.TextField(config);
                    return cmp;

                },
                createButton:function(s,e,a,config){
                    config.listeners.afterRender=function(sender){
                        if(a.value) {
                            sender.setText($app.$instance().$lang.getCaption(
                                            a.value,
                                           s.$$$module,
                                           $app.$instance().$lang.getLanguageCode()));
                        }
                        if (!sender.$$onClick) {
                            sender.$$onClick = function (callback) {
                                sender.$$onClickHandler = callback;
                            }
                        }
                    };
                    config.listeners.click=function(sender){
                        if(a.onClick){
                            $app.$instance().$events.fireEvent(s, a.onClick, [sender]);
                        }
                        if (sender.$$onClickHandler) {
                            sender.$$onClickHandler(sender);
                        }

                    };
                    if (a.icon) {
                        config.icon = "Icons/Button_" + a.icon + ".gif";
                    }
                    var parent = $(e[0]).parent("*[toolbar]");
                    if (parent.length > 0) {
                        config.xtype = "button";
                        $app.$linkToParent(e[0], "items", config);
                        e.remove();
                        return;
                    }
                    config.renderTo = e[0];
                    var cmp = new Ext.Button(config);
                    return cmp;
                },
                createDatePicker: function (s, e, a, config) {
                   
                   config.format= 'd/m/Y';
                   if (a.required) {
                        if (a.required != null) {
                            if (a.required != "") {
                                config.allowBlank = false;
                            }
                        }
                    }
                   a.format = $app.$instance().$salaryConfigs.$info().App_DateFormat;
                    if (a.format) {
                        if (a.format == "dd/MM/yyyy") {
                            config.format = "d/m/Y";
                        }
                        if (a.format == "dd/yyyy/MM") {
                            config.format = "d/Y/m";
                        }
                        if (a.format == "yyyy/dd/MM") {
                            config.format = "Y/d/m";
                        }
                        if (a.format == "MM/dd/yyyy") {
                            config.format = "m/d/Y";
                        }
                        if (a.format == "yyyy/dd/MM") {
                            config.format = "Y/d/m";
                        }
                    }
                    if (a.width) {
                        config.width = a.width * 1;
                    }
                  
                    config.listeners = {
                        change: function (sender) {
                            if (a.field) {
                                sender.$prevent = true;
                                $app.$instance().$parse(a.field).assign(s, sender.getValue());
                                s.$digest();
                                sender.$prevent = false;

                            }
                            if (a.onChange) {
                                $app.$instance().$events.fireEvent(s, a.onChange, sender, sender.getValue());
                            }
                        },
                        render:function(sender){
                            if (a.field) {
                                sender.setValue(s.$eval(a.field));
                                s.$watch(a.field, function (n, o) {
                                    if (sender.$prevent) return;
                                    if (angular.isDefined(n)) {
                                        sender.setValue(n);
                                    }
                                });
                            }
                        }
                        
                    };
                    var parent = $(e[0]).parent("*[toolbar]");
                    if (parent.length > 0) {
                        config.xtype = "datefield";
                        $app.$linkToParent(e[0], "items", config);
                        e.remove();
                        return;
                    }
                    config.renderTo = e[0];
                    var cmp = Ext.create('Ext.form.Date', config);
                    
                },
                createNumericInput: function (s, e, a, config) {
                    //this.initNumberField();
                 
                    if (a.decimalPrecision) {
                        config.decimalPrecision = a.decimalPrecision * 1;
                    }
                    if (a.hrpDecimalPrecision) {
                        config.decimalPrecision = $app.$instance().$sararyConfigs.$info()[a.hrpDecimalPrecision] * 1;
                    }
                   
                    if (a.width) {
                        config.width = a.width * 1;
                    }
                    config.listeners = {
                        change: function (sender,value) {
                            if (a.field) {
                                sender.$prevent = true;
                                $app.$instance().$parse(a.field).assign(s, sender.getValue());
                                s.$digest();
                                sender.$prevent = false;

                            }
                            if (a.onChange) {
                                $app.$instance().$events.fireEvent(s, a.onChange, [sender, sender.getValue()]);

                            }
                        },
                       
                        render: function (sender) {
                          
                            if (a.field) {
                                sender.setValue(s.$eval(a.field));
                                s.$watch(a.field, function (n, o) {
                                    if (sender.$prevent) return;
                                    if (angular.isUndefined(n)) return;
                                    if (n != o) {
                                        sender.setValue(n);
                                    }
                                });
                            }
                        }
                    };
                    
                    if (a.datatype == "int") {
                        config.alwaysDisplayDecimals = false;
                    }
                  
                    if (a.digits) {
                        var mDigits = a.digits * 1;
                        config.alwaysDisplayDecimals = true;
                        if (mDigits.toString()!="NaN") {
                            config.decimalPrecision = a.digits * 1;
                        }
                        else {
                            if (angular.isString(a.digits)) {
                                config.decimalPrecision = window.top.$salaryCongigs_$info[a.digits] * 1;
                            }
                        }
                    }
                    if (a.required == "true") {
                        config.$require = true;
                    }
                    Ext.util.Format.thousandSeparator = $app.$instance().$salaryConfigs.$info().App_NumberGroupSeparator;
                    Ext.util.Format.decimalSeparator = ($app.$instance().$salaryConfigs.$info().App_NumberGroupSeparator == ",") ? "." : ",";

                    config.format = "" + $app.$instance().$salaryConfigs.$info().App_NumberGroupSeparator + "0";
                    config.hideTrigger= true;
                    config.keyNavEnabled=false;
                    config.mouseWheelEnabled = false;

                    config.thousandSeparator = window.top.$salaryCongigs_$info.App_NumberGroupSeparator;
                    var parent = $(e[0]).parent("*[toolbar]");
                    if (parent.length > 0) {
                        config.xtype = "numericfield";
                        $app.$linkToParent(e[0], "items", config);
                        e.remove();
                        return;
                    }
                    config.renderTo = e[0];
                    var cmp = new Ext.ux.form.NumericField(config);
                  
                },
                createRadioButton: function (s, e, a,config) {

                },
                createCheckBox:function(s, e, a,config){
                
                    config.$cope = s;
                    config.listeners = {
                        change: function (sender, value) {
                            if (a.field) {
                                sender.$prevent = true;
                                $app.$instance().$parse(a.field).assign(s, value);
                                s.$diggest();
                                sender.$prevent = false;


                            }

                            if (a.onChange) {
                                $event.fireEvent(s, a.onChange, [sender, value]);
                            }
                        },
                        render: function (sender) {
                            if (a.field) {
                                s.$watch(a.field, function (n, o) {
                                    if (sender.$prevent) return;
                                    if (n != o) {
                                        sender.setValue(n);
                                    }
                                });
                            }
                        }
                    };
                  
                    if (a.title) {
                        config.boxLabel = $app.$instance().$lang.getCaption(a.title, s.$$$module);
                    }
                    var parent = $(e[0]).parent("*[toolbar]");
                    if (parent.length > 0) {
                        config.xtype = "checkbox";
                        $app.$linkToParent(e[0], "items", config);
                        e.remove();
                        return;
                    }
                    config.renderTo = e[0];
                    var cmp = Ext.create('Ext.form.Checkbox', config);
                    
                },
                createCombobox: function (s, e, a, config) {

                    $cbo.create(s, e, a, config);
                },
                createPassword: function (s, e, a, config) {
                  
                    if (a.required) {
                        if (a.required != null) {
                            if (a.required != "") {
                                config.allowBlank = false;
                            }
                        }
                    }
                    config.listeners = {
                        change: function (sender, value) {
                            if (a.field) {
                                sender.$prevent = true;
                                $app.$instance().$parse(a.field).assign(s, value);
                                sender.$prevent = false;
                                s.$watch(a.field, function (n, o) {
                                    if (sender.$prevent) return;
                                    if (n != o) {
                                        cmp.setValue(s.$eval(a.field));
                                    }
                                });
                            }
                            if (a.onChange) {
                                $event.fireEvent(s, a.onChange, [sender, value]);
                            }
                            
                        }
                    };

                    if (a.width) {
                        config.width = a.width * 1;
                    }
                    if (a.id) {
                        config.id = a.id + "_" + s.$root.$id;
                    }
                    if (a.title) {
                        config.blankText = $app.$instance().$lang.getCaption(a.title, s.$$$module);
                    }
                    config.renderTo=e[0];
                    var cmp = new Ext.form.TextField(config);

                  
                }
               
            }

        }
    ]);
HRP.directive("textarea", [
    '$application',
    function ($app) {
    return {
            restrict: "E",
            template: "<div  ng-transclude></div>",
            replace: true,
            transclude: true,
            scope: false,
            compile: function (e, a) {
                return function (s, e, a) {
                    var scope = $app.$instance().$loader.getScope(s, a);
                    var config = $app.$instance().$loader.$generateConfig(scope, e, a);
                    config.renderTo = e[0];
                    config.listeners = {
                        afterrender: function (sender) {
                            if (a.field) {

                                s.$watch(a.field, function (n, o) {
                                    if (n != o) {
                                        sender.setValue(n);
                                    }
                                });

                            }
                        },
                        change: function (sender, value) {
                            sender.$prevent = true;
                            $app.$instance().$parse(a.field).assign(s, value);
                            s.$digest();
                            sender.$prevent = false;
                        }
                    };
                    if (a.width) {
                        config.width = a.width * 1;
                    }
                    if (a.height) {
                        config.height = a.height * 1;
                    }
                    var cmp = new Ext.form.TextArea(config);
                }
            }
        }
    }]);


Ext.onReady(function () {
   
    Ext.define('Ext.ux.form.NumericField',
 {
     extend: 'Ext.form.field.Number',//Extending the NumberField
     alias: 'widget.numericfield',//Defining the xtype,
     currencySymbol: null,
     useThousandSeparator: true,
     thousandSeparator:',',
     alwaysDisplayDecimals: true,
     initComponent: function () {
         if (this.useThousandSeparator && this.decimalSeparator == ',' && this.thousandSeparator == ',')
             this.thousandSeparator = '.';
         else
             if (this.allowDecimals && this.thousandSeparator == '.' && this.decimalSeparator == '.')
                 this.decimalSeparator = ',';

         this.callParent(arguments);
     },
     setValue: function (value) {
         if (angular.isUndefined(value)) {
             value = 0;
         }
        // Ext.ux.form.NumericField.superclass.setValue.call(this, value != null ? value.toString().replace('.', this.decimalSeparator) : value);

         this.setRawValue(this.getFormattedValue(value));
     },
     getFormattedValue: function (value) {
         if (Ext.isEmpty(value) || !this.hasFormat())
             return value;
         else {
             var neg = null;
             value = value * 1;
             value = (neg = value < 0) ? value * -1 : value;
             value = this.allowDecimals && this.alwaysDisplayDecimals ? value.toFixed(this.decimalPrecision) : value;

             if (this.useThousandSeparator) {
                 if (this.useThousandSeparator && Ext.isEmpty(this.thousandSeparator))
                     throw ('NumberFormatException: invalid thousandSeparator, property must has a valid character.');

                 if (this.thousandSeparator == this.decimalSeparator)
                     throw ('NumberFormatException: invalid thousandSeparator, thousand separator must be different from decimalSeparator.');

                 value = value.toString();

                 var ps = value.split('.');
                 ps[1] = ps[1] ? ps[1] : null;

                 var whole = ps[0];

                 var r = /(\d+)(\d{3})/;

                 var ts = this.thousandSeparator;

                 while (r.test(whole))
                     whole = whole.replace(r, '$1' + ts + '$2');

                 value = whole + (ps[1] ? this.decimalSeparator + ps[1] : '');
             }

             return Ext.String.format('{0}{1}{2}', (neg ? '-' : ''), (Ext.isEmpty(this.currencySymbol) ? '' : this.currencySymbol + ' '), value);
         }
     },
     /**
      * overrides parseValue to remove the format applied by this class
      */
     parseValue: function (value) {
         //Replace the currency symbol and thousand separator
         return Ext.ux.form.NumericField.superclass.parseValue.call(this, this.removeFormat(value));
     },
     /**
      * Remove only the format added by this class to let the superclass validate with it's rules.
      * @param {Object} value
      */
     removeFormat: function (value) {
         if (Ext.isEmpty(value) || !this.hasFormat())
             return value;
         else {
             value = value.toString().replace(this.currencySymbol + ' ', '');

             value = this.useThousandSeparator ? value.replace(new RegExp('[' + this.thousandSeparator + ']', 'g'), '') : value;

             return value;
         }
     },
     /**
      * Remove the format before validating the the value.
      * @param {Number} value
      */
     getErrors: function (value) {
         return Ext.ux.form.NumericField.superclass.getErrors.call(this, this.removeFormat(value));
     },
     hasFormat: function () {
         return this.decimalSeparator != '.' || (this.useThousandSeparator == true && this.getRawValue() != null) || !Ext.isEmpty(this.currencySymbol) || this.alwaysDisplayDecimals;
     },
     /**
      * Display the numeric value with the fixed decimal precision and without the format using the setRawValue, don't need to do a setValue because we don't want a double
      * formatting and process of the value because beforeBlur perform a getRawValue and then a setValue.
      */
     onFocus: function () {
         //this.setRawValue(this.removeFormat(this.getRawValue()));
         this.setRawValue(this.getNumber());
         this.callParent(arguments);
     },
     onBlur:function(){
         
         this.setRawValue(this.getFormattedValue(this.getValue()));
     },
     getValue: function () {
         var n = this.getRawValue();
         if (n == null) {
             if (this.$require) {
                 return 0;
             }
             else {
                 return null;
             }
         }
         if (angular.isNumber(n)) {
             return n;
         }
         var deCStr = (this.thousandSeparator == ",") ? "." : ",";
         var ret = this.removeFormat(n);
         var items = ret.split(deCStr);
         if (items.length == 1) {
             return ret * 1;
         }
         else {
             var num = ret.replace(deCStr, '') * 1;
             var fRet = num / Math.pow(10, items[1].length);
             return fRet;
         }
     }
 });

});